﻿using System.Linq;
using System.IO;

namespace DuplicateFileFinder.Business
{
    public class FileComparer
    {
        public CompareResult Compare(string filePath1, string filePath2)
        {
            var fsin1 = new FileStream(filePath1, FileMode.Open);
            var fsin2 = new FileStream(filePath2, FileMode.Open);

            if (fsin1.Length != fsin2.Length)
                return CompareResult.Unequal;

            var bytes1 = new byte[(fsin1.Length > 1024 * 1024) ? 1024 * 1024 : fsin1.Length];
            var bytes2 = new byte[bytes1.Length];

            try
            {
                while (fsin1.Read(bytes1, 0, bytes1.Length) != 0)
                {
                    fsin2.Read(bytes2, 0, bytes2.Length);
                    if (!bytes1.SequenceEqual(bytes2))
                        return CompareResult.Unequal;
                }
            }
            catch (IOException ex)
            {
                return CompareResult.Unknown;
            }

            return CompareResult.Equal;
        }
    }
}
